#include "UdpServer.hpp"

// ./client 127.0.0.1 8899
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "指令错误: ./server ip port" << std::endl;
    }
    uint16_t port = std::stoi(argv[2]);
    std::string ip = argv[1];

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = inet_addr(ip.c_str());
    int n = ::bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));

    struct sockaddr recv_addr;
    socklen_t len = sizeof(recv_addr);
    // 客户端
    while (true)
    {
        // 先发消息，然后收消息
        std::cout << "[Enter Message]# ";
        std::string send_message;
        std::getline(std::cin, send_message);
        int res_send = sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
        if (res_send == -1)
        {
            std::cout << "发送失败" << std::endl;
            exit(errno);
        }
        std::cout << "发送成功: " << send_message << " -> " << send_message.size() << std::endl;

        char *recv_message = new char[1024];
        //char recv_message[1024] = {0};
        int res_recv = recvfrom(sockfd, recv_message, sizeof(recv_message) - 1, 0, (struct sockaddr *)&recv_addr, &len);
        if (res_recv == -1)
        {
            std::cout << "接收失败" << std::endl;
            exit(errno);
        }
        recv_message[res_recv] = 0;
        std::cout << "接收成功: " << recv_message << std::endl;
        delete[] recv_message;
    }
    return 0;
}